package com.dao;


import org.hibernate.*;

import java.io.Serializable;
import java.util.*;
import com.util.DBManager;

public class BaseDAO {
	Session session;
	Transaction tx;
	Query query;
	List list;

	public Serializable add(Object obj) {
		Serializable id = 0;
		try {
            session = DBManager.getSession();    //获取session
            tx = session.beginTransaction();     //开启事务
            id = session.save(obj);              //保存对象
            tx.commit();                       //把事物保存到数据库里
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			session.close();
		}
		return id;
		
	}
	
	
	public void del(Object obj) {
		try {
            session = DBManager.getSession();
            tx = session.beginTransaction();
            session.delete(obj);
            tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			session.close();
		}
		
	}
	
	public void update(Object obj) {
		try {
            session = DBManager.getSession();
            tx = session.beginTransaction();
            session.update(obj);
            tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			session.close();
		}
	}
	
	public List show(String hql) {
		try {
            session = DBManager.getSession();
            query = session.createQuery(hql);
            list = query.list();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			session.close();
		}
		return list;
		
	}
	
	
	public List find(String hql,Object[] params) {
		try {
            session = DBManager.getSession();
            query = session.createQuery(hql);
            if(params!=null){
            	for(int i = 0;i<params.length;i++){
            		query.setParameter(i,params[i]);
            	}
            }
            list = query.list();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			session.close();
		}
		return list;
		
	}
	
	public Object findByID(Class clazz,Serializable id) {
		Object obj = null;
		try {
            session = DBManager.getSession();
            obj = session.get(clazz,id);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			session.close();
		}
		return obj;
		
	}
	
	
	public void operate(String hql,Object[] params){
		try {
            session = DBManager.getSession();
            tx = session.beginTransaction();
            query = session.createQuery(hql);
            if(params!=null){
            	for(int i = 0;i<params.length;i++){
            		query.setParameter(i,params[i]);
            	}
            }
            query.executeUpdate();
            tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			session.close();
		}
	}
}
